"""
识别视图
最后修改：3.36
修改人：陈泯全
"""
import configparser
import os
from flask import Blueprint, request, current_app

from logs.LogClass import Mylogger
from utils.tools import safe_base64_decode, get_imageNdarrayFromDir, process_imageNdarray
import requests
import json
from service.DistinguishService import distinguishSevice

bp = Blueprint("DistingSubSys", __name__, url_prefix="/DistingSubSys")
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

# 1.获取根目录
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 2. 设置日志解析实例
cf = configparser.ConfigParser()
# 3.读取日志文件
cf.read(root_path + "/logs/log.conf")
# 4. 创建自定义日志类的实例对象
logger = Mylogger(root_path + cf.get("log", "LOG_PATH"), cf.get("log", "LOG_NAME")).get_logger()


@bp.route('/Service', methods=['GET', 'POST'])
def service():
    if request.method == 'POST':
        standardlabel={}
        # 获取图片的名字,获取的参数为image_name,参数在url上面
        image_name = request.args.get('image_name')
        # 获取到标准lable
        with open('./AgriculturalDisease_validation_annotations.json', 'r', encoding='utf8')as fp:
            # 读取json文件
            json_data = json.load(fp)
            for i in json_data:
                if i['image_id'] == image_name:
                    standardlabel = distinguishSevice().CATEGORY_LIST[i['disease_class']]
        file_obj = request.data
        path = safe_base64_decode(str(file_obj))
        img = get_imageNdarrayFromDir(path)
        img = process_imageNdarray(img)
        service = distinguishSevice(modelIp='192.168.0.210')
        dict = service.serving(img)
        # 这里添加日志信息
        dictlabel = dict.get('species') + '-' + dict.get('disease') + '-' + dict.get('level')
        logger.info(image_name+' '+standardlabel + ' ' + dictlabel)
        return dict


@bp.route('/Test', methods=['GET'])
def modelTest():
    dict = {}
    dic = {}
    dict['status'] = -1
    dict['meanValue'] = -1
    dict['meanTime'] = -1
    service = distinguishSevice(modelIp='192.168.0.210')
    try:
        status = requests.get(service.SERVER_URL_STATUS)
        byte = status.content
        data = byte.decode(encoding="utf-8")
        dic = json.loads(data)
    except Exception as r:
        current_app.logger.error(r)
        dict.update(dic)
        return dict
    imgdir = './static/apple_blackheart_bad.JPG'
    status, meanValue, meanTime = service.test(imgdir)
    stauts = status
    dict['status'] = stauts
    dict['meanValue'] = meanValue
    dict['meanTime'] = meanTime

    dict.update(dic)
    return dict


@bp.route('/')
def index():
    return {
        "status": 'ok'
    }
